package com.itheima.springbootwebtlias.controller;

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import com.itheima.springbootwebtlias.pojo.Result;
import com.itheima.springbootwebtlias.util.AliyunOSSOperator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

//处理文件上传的处理器
@Slf4j
@RestController
public class UploadController {

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        log.info("文件上传，文件名：{}", file);
        //1.接收请求参数：接收文件，MultipartFile

        //2.使用工具类，实现文件上传到阿里云服务器中
        String imagePath = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());

        return Result.success(imagePath); //code = 1 ,msg = success ,data = 文件访问路径


        /*
            MultipartFile：表示上传的文件
              功能方法：
                 transferTo(File 目标位置)：将接收到的文件转存到磁盘的文件中
                 getOriginalFilename()：获取上传的文件的原始文件名
                 getInputStream()：获取上传的文件的输入流
         */
        /*
        //1.截取源文件的类型：.jpg   .png  .exe   .mp4   .doc
        //xxx.jpg
        String type = image.getOriginalFilename()
                .substring(image.getOriginalFilename().lastIndexOf("."));

        //2.生成新的不重复的文件名称：UUID.randomUUID().toString()
        String fileName = UUID.randomUUID().toString() + type;

        //3.使用新的文件名称，拼接文件类型，存储文件
        //image.transferTo(new File("d://upload//"+fileName));


        //3.上传到阿里云oss服务器上
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-nanjing.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "tlias-xhq";

        // 填写Bucket所在地域。以华东1（杭州）为例，Region填写为cn-hangzhou。
        String region = "cn-nanjing";

        // 创建OSSClient实例。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, image.getInputStream());
            // 上传字符串。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }*/

    }
}
